/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2024 All Rights Reserved.
 */
package com.alipay.demo.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.alipay.demo.service.AntMerchantShopService;
import com.alipay.demo.service.MarketingCertificateService;
import com.alipay.demo.util.AlipayApiCallback;
import com.alipay.demo.util.AlipayApiTemplate;
import com.alipay.demo.util.AlipaySdkUtil;
import com.alipay.demo.vo.CertificationRefundConfirmCommitRequest;
import com.alipay.demo.vo.CertificationRefundRequest;
import com.alipay.demo.vo.CertificationUseRequest;
import com.alipay.demo.vo.OpenResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author jishupei.jsp
 * @version : MarketingCertificateServiceImpl, v0.1 2024年03月15日 12:06 下午 jishupei.jsp Exp $
 */
@Service
public class MarketingCertificateServiceImpl implements MarketingCertificateService {

    @Autowired
    private AlipaySdkUtil alipaySdkUtil;

    @Autowired
    private AntMerchantShopService antMerchantShopService;

    @Override
    public OpenResponse<AlipayMarketingCertificateCertificationPrepareuseResponse> certificationPrepareUse(String code, String encryptedData, Boolean crossOrder) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<AlipayMarketingCertificateCertificationPrepareuseResponse, AlipayMarketingCertificateCertificationPrepareuseResponse>() {
            @Override
            public AlipayMarketingCertificateCertificationPrepareuseResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayMarketingCertificateCertificationPrepareuseRequest request = new AlipayMarketingCertificateCertificationPrepareuseRequest();
                AlipayMarketingCertificateCertificationPrepareuseModel model = new AlipayMarketingCertificateCertificationPrepareuseModel();

                if (!StringUtils.isEmpty(code)) {
                    // 设置券码
                    model.setCode(code);
                }

                if (!StringUtils.isEmpty(encryptedData)) {
                    // 设置加密数据
                    model.setEncryptedData(encryptedData);
                }

                // 设置是否开启跨单核销
                model.setCrossOrder(crossOrder);

                request.setBizModel(model);
                return alipaySdkUtil.execute(request);
            }

            @Override
            public AlipayMarketingCertificateCertificationPrepareuseResponse getData(AlipayMarketingCertificateCertificationPrepareuseResponse response) {
                return response;
            }

            @Override
            public String getApiName() {
                return "alipay.marketing.certificate.certification.prepareuse";
            }
        });
    }

    @Override
    public OpenResponse<List<CertificateUseResult>> certificationUse(CertificationUseRequest useRequest) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<List<CertificateUseResult>, AlipayMarketingCertificateCertificationUseResponse>() {

            @Override
            public AlipayMarketingCertificateCertificationUseResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayMarketingCertificateCertificationUseRequest request = new AlipayMarketingCertificateCertificationUseRequest();
                AlipayMarketingCertificateCertificationUseModel model = new AlipayMarketingCertificateCertificationUseModel();

                // 设置核销时间
                model.setBizDt(new Date());

                // 设置凭证核销详情
                List<CertificateUseInfo> certificateUseInfoList = new ArrayList<>();
                CertificateUseInfo certificateUseInfoList0 = new CertificateUseInfo();
                if (!StringUtils.isEmpty(useRequest.getEncryptedCode())) {
                    certificateUseInfoList0.setEncryptedCode(useRequest.getEncryptedCode());
                } else {
                    certificateUseInfoList0.setCode(useRequest.getCode());
                }
                certificateUseInfoList.add(certificateUseInfoList0);
                model.setCertificateUseInfoList(certificateUseInfoList);

                // 设置购买商品的订单id
                model.setOrderId(useRequest.getOrderId());

                // 设置外部业务单号
                model.setOutBizNo(outBizNoGenerator());

                // 设置核销门店id
                if (StringUtils.isEmpty(useRequest.getShopId())) {
                    // 默认查第一个正常状态的门店
                    List<ShopQueryOpenApiVO> shopQueryOpenApiVOS = antMerchantShopService.queryNormalShopInfos();
                    if (CollectionUtils.isEmpty(shopQueryOpenApiVOS)) {
                        throw new AlipayApiException("无正常状态门店");
                    }
                    model.setShopId(shopQueryOpenApiVOS.get(0).getShopId());
                } else {
                    model.setShopId(useRequest.getShopId());
                }

                // uid参数未来计划废弃，存量商户可继续使用，新商户请使用openid。请根据应用-开发配置-openid配置选择支持的字段。
                if (StringUtils.isEmpty(useRequest.getUserIdOrOpenId()) || useRequest.getUserIdOrOpenId().startsWith("2088")) {
                    model.setUserId(useRequest.getUserIdOrOpenId());
                } else {
                    model.setOpenId(useRequest.getUserIdOrOpenId());
                }

                request.setBizModel(model);

                return alipaySdkUtil.execute(request);
            }

            @Override
            public List<CertificateUseResult> getData(AlipayMarketingCertificateCertificationUseResponse response) {
                return response.getCertificateUseResultList();
            }

            @Override
            public String getApiName() {
                return "alipay.marketing.certificate.certification.use";
            }
        });
    }

    @Override
    public OpenResponse<List<CertificateReverseResult>> certificationRefund(CertificationRefundRequest refundRequest) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<List<CertificateReverseResult>, AlipayMarketingCertificateCertificationRefundResponse>() {

            @Override
            public AlipayMarketingCertificateCertificationRefundResponse process() throws AlipayApiException {
                AlipayMarketingCertificateCertificationRefundRequest request = new AlipayMarketingCertificateCertificationRefundRequest();
                AlipayMarketingCertificateCertificationRefundModel model = new AlipayMarketingCertificateCertificationRefundModel();
                model.setOutBizNo(outBizNoGenerator());
                if (StringUtils.isEmpty(refundRequest.getUserIdOrOpenId()) || refundRequest.getUserIdOrOpenId().startsWith("2088")) {
                    model.setUserId(refundRequest.getUserIdOrOpenId());
                } else {
                    model.setOpenId(refundRequest.getUserIdOrOpenId());
                }
                model.setUseOrderNoList(refundRequest.getUseOrderNoList());
                request.setBizModel(model);

                return alipaySdkUtil.execute(request);
            }

            @Override
            public List<CertificateReverseResult> getData(AlipayMarketingCertificateCertificationRefundResponse response) {
                return response.getCertificateReverseResultList();
            }

            @Override
            public String getApiName() {
                return "alipay.marketing.certificate.certification.refund";
            }
        });
    }

    @Override
    public OpenResponse<Void> orderRefundConfirmCommit(CertificationRefundConfirmCommitRequest commitRequest) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<Void, AlipayMarketingCertificateOrderRefundconfirmcommitResponse>() {
            @Override
            public AlipayMarketingCertificateOrderRefundconfirmcommitResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayMarketingCertificateOrderRefundconfirmcommitRequest request = new AlipayMarketingCertificateOrderRefundconfirmcommitRequest();
                AlipayMarketingCertificateOrderRefundconfirmcommitModel model = new AlipayMarketingCertificateOrderRefundconfirmcommitModel();

//                // 设置凭证标识ID
//                model.setCertificateId(certificateId);

                // 设置退款前向商户确认退款结果
                model.setResult(commitRequest.getResult());

                if (!StringUtils.isEmpty(commitRequest.getReason())) {
                    // 设置拒绝原因
                    model.setReason(commitRequest.getReason());
                }

                // uid参数未来计划废弃，存量商户可继续使用，新商户请使用openid。请根据应用-开发配置-openid配置选择支持的字段。
                if (StringUtils.isEmpty(commitRequest.getUserIdOrOpenId()) || commitRequest.getUserIdOrOpenId().startsWith("2088")) {
                    model.setUserId(commitRequest.getUserIdOrOpenId());
                } else {
                    model.setUserOpenId(commitRequest.getUserIdOrOpenId());
                }

                // 设置订单号
                model.setOrderId(commitRequest.getOrderId());

                request.setBizModel(model);

                return alipaySdkUtil.execute(request);
            }

            @Override
            public Void getData(AlipayMarketingCertificateOrderRefundconfirmcommitResponse response) {
                return null;
            }

            @Override
            public String getApiName() {
                return "alipay.marketing.certificate.order.refundconfirmcommit";
            }
        });
    }

    @Override
    public OpenResponse<List<CertificateQueryInfo>> certificationQuery(String orderId, List<String> certificateIdList, String userIdOrOpenId) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<List<CertificateQueryInfo>, AlipayMarketingCertificateCertificationBatchqueryResponse>() {

            @Override
            public AlipayMarketingCertificateCertificationBatchqueryResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayMarketingCertificateCertificationBatchqueryRequest request = new AlipayMarketingCertificateCertificationBatchqueryRequest();
                AlipayMarketingCertificateCertificationBatchqueryModel model = new AlipayMarketingCertificateCertificationBatchqueryModel();

                if (!CollectionUtils.isEmpty(certificateIdList)) {
                    // 设置凭证ID列表
                    model.setCertificateIdList(certificateIdList);
                }
                if (!StringUtils.isEmpty(orderId)) {
                    // 设置购买商品的订单id
                    model.setOrderId(orderId);
                }

                // uid参数未来计划废弃，存量商户可继续使用，新商户请使用openid。请根据应用-开发配置-openid配置选择支持的字段。
                if (StringUtils.isEmpty(userIdOrOpenId) || userIdOrOpenId.startsWith("2088")) {
                    model.setUserId(userIdOrOpenId);
                } else {
                    model.setOpenId(userIdOrOpenId);
                }

                request.setBizModel(model);

                return alipaySdkUtil.execute(request);
            }

            @Override
            public List<CertificateQueryInfo> getData(AlipayMarketingCertificateCertificationBatchqueryResponse response) {
                return response.getCertificateInfoList();
            }

            @Override
            public String getApiName() {
                return "alipay.marketing.certificate.certification.batchquery";
            }
        });
    }

    @Override
    public OpenResponse<AlipayMarketingCertificateUserBatchqueryResponse> certificationList(Long pageNum, Long pageSize, String userIdOrOpenId, String certificateStatus) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<AlipayMarketingCertificateUserBatchqueryResponse, AlipayMarketingCertificateUserBatchqueryResponse>() {
            @Override
            public AlipayMarketingCertificateUserBatchqueryResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayMarketingCertificateUserBatchqueryRequest request = new AlipayMarketingCertificateUserBatchqueryRequest();
                AlipayMarketingCertificateUserBatchqueryModel model = new AlipayMarketingCertificateUserBatchqueryModel();

                // 设置分页查询页码
                model.setPageNum(pageNum == null ? 1L : pageNum);

                // 设置分页查询单页数据条数
                model.setPageSize(pageSize == null ? 10L : pageSize);

                // uid参数未来计划废弃，存量商户可继续使用，新商户请使用openid。请根据应用-开发配置-openid配置选择支持的字段。
                if (StringUtils.isEmpty(userIdOrOpenId) || userIdOrOpenId.startsWith("2088")) {
                    model.setUserId(userIdOrOpenId);
                } else {
                    model.setOpenId(userIdOrOpenId);
                }

                if (!StringUtils.isEmpty(certificateStatus)) {
                    // 设置凭证状态
                    model.setCertificateStatus(certificateStatus);
                }

                request.setBizModel(model);
                return alipaySdkUtil.execute(request);
            }

            @Override
            public AlipayMarketingCertificateUserBatchqueryResponse getData(AlipayMarketingCertificateUserBatchqueryResponse response) {
                return response;
            }

            @Override
            public String getApiName() {
                return "alipay.marketing.certificate.user.batchquery";
            }
        });
    }

    private String outBizNoGenerator() {
        Random random = new Random();
        // 生成一个八位数的随机数字
        return String.format("%08d", random.nextInt(100000000));
    }
}
